<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Home extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $this->load->helper('file');
		$this->load->helper('form');
        $this->load->helper('fuc');
        $this->load->library('topclass');
        $this->load->library('session_db');
        $this->load->model('generat_array');
        $this->load->database();
        $this->load->model("auth_handle");
        $this->config->load('topapiconfig');
        $this->config->load('comments_gsetting');
        $this->auth_handle->isLogin_statues();
        $this->auth_handle->decis_last_time();
    }

    public function commnetwall() {
        $data['commnetwall'] = $this->commnetwall();
        $this->load->view('index_view', $data);
    }

    private function get_userarray() {//这个为了获取用户的数组信息，private先放在control中
        $userid_my = $this->session_db->get_Sessiondb("userid_my");
        $sql = "select * from user where  user_id=\"{$userid_my}\"";
        $query = $this->db->query($sql);
        return $res = $query->result_array();
    }

    private function get_configarray() {//这个为了获取config表的数组，private先放在control中
        $userid_my = $this->session_db->get_Sessiondb("userid_my");
        $sql = "select * from config where  user_id=\"{$userid_my}\"";
        $query = $this->db->query($sql);
        return $res = $query->result_array();
    }
	
	
	
    public function index($width=750) {		
		$users_array = $this->get_userarray();
		if( !count($users_array)){
			redirect('login/index', 'location', 301);
		}
		$data["user"] = $users_array[0];
		$configseting_array = $this->get_configarray();
		if(empty($configseting_array)){
			$configseting_array[0] = array(
											'style_id' => 1,
											'min_txt_num' => 5,
											'visual' => 1,
											'intervall' => 50,
											'hebing' => 1,
											'hebingnum' => 5
										);
		}
		$data['configseting'] = $configseting_array[0];
		/*
		$sessinkey = $this->session_db->get_Sessiondb("top_session"); //打印登陆用户授权后获得的top_session或者sessionkey
        //$configarray = $this->config->item('new_app');
        //$sessinkey = $configarray["sessionkey"];//程序测试时候人为设定top_session或者sessionkey
		
		//得到20条满足config条件的评论 从第一页开始，第三个参数是每页条数
		$comment_array = array(); 
		for($p=1;$p<100;$p++){
			$tmp = $this->wallArray($sessinkey,$p,35,$configseting_array[0]['min_txt_num']);
			if( !is_array($tmp))  break;
			$comment_array = array_merge($comment_array,$tmp);
			if(count($comment_array) >= 10) break;
		}
			
        $data['commnetwall'] = $comment_array;*/
		
        $this->db->where('shop_id',$users_array[0]['shop_id']);
		$r = $this->db->get('wallcode');
		if($r->num_rows() > 0){
			$wallcode = $r->row_array();
			$data["commnetwall"] = unserialize($wallcode['codearray']);
			$data["up_time"] = $wallcode['up_time'];
		}else{
			redirect('home/update', 'location', 301);
		}
		

        $data['menu'] = 'index';
		$data['width'] = $width;

        $this->load->view('header_view', $data);
        $this->load->view('index_view');
        $this->load->view('footer_view');
    }
	

    //配置参数
    public function set() {
        $data['menu'] = 'login';
        $users_array = $this->get_userarray();
		if( !count($users_array)){
			redirect('login/index', 'location', 301);
		}
		$data["user"] = $users_array[0];
		
		$userid_my = $this->session_db->get_Sessiondb("userid_my"); //获取sessiondb中的系统自定义uid
        $sql = "select * from config where user_id=\"{$userid_my}\" ";
        $query = $this->db->query($sql);
        $res = $query->result_array();
		
		if (empty($res)) {
            $data['configarray'] = array(
											'style_id' => 1,
											'min_txt_num' => 5,
											'visual' => 1,
											'intervall' => 50,
											'hebing' => 0,
											'hebingnum' => 5
										);
        } else {
            $data['configarray'] = $res[0];
        }
		$this->load->view('header_view', $data);
        $this->load->view('set_view');
        $this->load->view('footer_view');
    }

    public function config() {
        $userid_my = $this->session_db->get_Sessiondb("userid_my"); //获取sessiondb中的系统自定义uid
        $sql = "select * from config where user_id=\"{$userid_my}\"";
        $query = $this->db->query($sql);
        $res = $query->result_array();

        if (empty($res)) {
            $insertsql = "insert into config (user_id,style_id,min_txt_num,visual,intervall,hebing,hebingnum) values
(\"{$userid_my}\",\"{$_POST["effect"]}\",\"{$_POST["min_txt_num"]}\",\"{$_POST["visual"]}\",\"{$_POST["intervall"]}\",\"{$_POST["hebing"]}\",\"{$_POST["hebingnum"]}\")";
            $this->db->query($insertsql);
        } else {
            $updatesql = "update config set style_id=\"{$_POST["effect"]}\",min_txt_num=\"{$_POST["min_txt_num"]}\",visual=\"{$_POST["visual"]}\", intervall=\"{$_POST["intervall"]}\", hebing=\"{$_POST["hebing"]}\", hebingnum=\"{$_POST["hebingnum"]}\" where user_id=\"{$userid_my}\"";
            $this->db->query($updatesql);
        }
        redirect('home/set/done', 'location');
        // print_r($_POST);
    }
	
	
	//update更新好评数据
	public function update(){
			$data['menu'] = 'update';
			
			$users_array = $this->get_userarray();
			if( !count($users_array)){
				redirect('login/index', 'location', 301);
			}
			$data["user"] = $users_array[0];
			
			$this->db->where('shop_id',$users_array[0]['shop_id']);
			$r = $this->db->get('wallcode');
			$data["wallcode"] = $r->row_array();
			
			$this->load->view('header_view', $data);
            $this->load->view('update_view');
			$this->load->view('footer_view');
		}
	
	//好评筛选
	public function wallArray($sessinkey,$setPageNo=1,$setPageSize=20,$min_txt_num=1,$hebing=1,$hebingnum=3){
		    $res = $this->topclass->api_TraderatesGetRequest("TraderatesGetRequest", $sessinkey,$setPageNo,$setPageSize);
			objectToArray(&$res);
			$total_results = $res['total_results'];
			if($total_results == 0 ) return false; //一套评价也没有的时候
			if($total_results <= ($setPageNo-1)*$setPageSize)  return false;
			$trade_rate = $res["trade_rates"]["trade_rate"];
			
			if($total_results > 0) : /* 好评数大于0的时候，结果大于1 则直接赋给$comment_array，=1 则转换成二维数组 */
				if( isset($trade_rate[1])){
					$com_array = $trade_rate;
				}else{
					$com_array[] = $res["trade_rates"]["trade_rate"];
				}
			else :
				return $com_array = false;
			endif;
			$comment_array = array(); //传入有交易和评论的app对应key，所以如果前台没有显示则表示
			$_num_iid = array();// 宝贝id临时数组
			//topclass。php的line19 ：引入配置app
			if (is_array($com_array)) {
				foreach ($com_array as $key => $val) {
					if(mb_strlen($val["content"]) < $min_txt_num || strpos($val["content"],'系统默认好评')) continue;

					if($hebing){ //合并评论
						if( !array_key_exists($val["num_iid"],$_num_iid)) : //如果当前di不存在临时数组中
							$itempic_url = $this->generat_array->get_itemurl_byid($val["num_iid"]);
							if( !$itempic_url) continue;
							$_num_iid[$val["num_iid"]] = $key; //则把当前di放入临时数组
							$comment_array[$key]["num_iid"] = $val["num_iid"];
							$comment_array[$key]["itempic_url"] = $itempic_url;
							$comment_array[$key]["item_price"] = $val["item_price"];
							$comment_array[$key]["item_title"] = $val["item_title"];
							$comment_array[$key]['praise'][] = array(
																		 'created'=>$val["created"],
																		 'buy_nick'=>$val["nick"],
																		 'content'=>$val["content"],
																		 //'buy_avter'=>"暂时无法获取api",
																		 //'buy_level'=>"暂时无法获取api"
																	 );
						else :
							if(count($comment_array[$_num_iid[$val["num_iid"]]]['praise']) > $hebingnum) continue;
							$comment_array[$_num_iid[$val["num_iid"]]]['praise'][] = array(
																		 'created'=>$val["created"],
																		 'buy_nick'=>$val["nick"],
																		 'content'=>$val["content"],
																		 //'buy_avter'=>"暂时无法获取api",
																		 //'buy_level'=>"暂时无法获取api"
																	 );
						endif;
					}else{ //不合并评论
						$itempic_url = $this->generat_array->get_itemurl_byid($val["num_iid"]);
						if( !$itempic_url) continue;
						$comment_array[$key]["num_iid"] = $val["num_iid"];
						$comment_array[$key]["itempic_url"] = $itempic_url;
						$comment_array[$key]["item_price"] = $val["item_price"];
						$comment_array[$key]["item_title"] = $val["item_title"];
						$comment_array[$key]['praise'][] = array(
																	 'created'=>$val["created"],
																	 'buy_nick'=>$val["nick"],
																	 'content'=>$val["content"],
																	 //'buy_avter'=>"暂时无法获取api",
																	 //'buy_level'=>"暂时无法获取api"
																 );
					}//end 不合并
				}
			}
			return $comment_array;
	}
	
	//好评数组序列化以后保存到数据库
	public function updateSave(){
		if($this->input->post('update_submit')) : 

			$users_array = $this->get_userarray();
			if( !count($users_array)){
				redirect('login/index', 'location', 301);
			}
			
			$uptype = $this->input->post('uptype'); //第一次插入还是 以后的更新
			
			$configseting_array = $this->get_configarray();
			if(empty($configseting_array)){
				$configseting_array[0] = array(
												'style_id' => 1,
												'min_txt_num' => 5,
												'visual' => 1,
												'intervall' => 50,
												'hebing' => 0,
												'hebingnum' => 5
											);
			}
	
			$sessinkey = $this->session_db->get_Sessiondb("top_session"); //打印登陆用户授权后获得的top_session或者sessionkey
			//$configarray = $this->config->item('new_app');
			//$sessinkey = $configarray["sessionkey"];//程序测试时候人为设定top_session或者sessionkey
			
			//得到20条满足config条件的评论 从第一页开始，第三个参数是每页条数
			$comment_array = array(); 
			for($p=1;$p<100;$p++){
				$tmp = $this->wallArray($sessinkey,$p,35,$configseting_array[0]['min_txt_num'],(int)$configseting_array[0]['hebing'],(int)$configseting_array[0]['hebingnum']);
				if( !is_array($tmp))  break;
				$comment_array = array_merge($comment_array,$tmp);
				if(count($comment_array) >= 40) break;
			}
			$codeArray = serialize($comment_array);
			if($uptype == 'insert'){
				$this->db->insert('wallcode',array('shop_id'=>$users_array[0]['shop_id'],'codearray'=>$codeArray,'up_time'=>time()));
			}else{
				$this->db->where('shop_id',$users_array[0]['shop_id']);
				$this->db->update('wallcode',array('codearray'=>$codeArray,'up_time'=>time()));	
			}
			redirect('home/update/done', 'location', 301);
		else :
			redirect('login/index', 'location', 301);
		endif;
	}
	
	
	//使用帮助
	public function intro(){
			$data['menu'] = 'intro';
			
			$users_array = $this->get_userarray();
			if( !count($users_array)){
				redirect('login/index', 'location', 301);
			}
			$data["user"] = $users_array[0];
			
			$this->load->view('header_view', $data);
            $this->load->view('intro_view');
			$this->load->view('footer_view');
	}
	
	
	
	
	
	

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */